import { Input, Drawer, Form, Select, Upload, Button, message } from "antd";
import ImgCrop from "antd-img-crop";
import type { SelectProps } from "antd";
import type { GetProp, UploadFile, UploadProps } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { setOpen } from "@/store/modules/publishArticle";
import { useEffect, useState } from "react";
import { UploadApi } from "@/http/api/upload";
import { CreateArticleApi } from "@/http/api/article";
import { GetLabelListApi } from "@/http/api/publishArticle";
import { useNavigate } from "react-router-dom";
import publishDrawerLess from "./index.module.less";
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
/* interface DataNodeType {
  value: string;
  label: string;
  children?: DataNodeType[];
} */

function PublishDrawer(props: any) {
  const openFlag = useSelector((state: any) => state.publishArticle.openFlag);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [form] = Form.useForm();

  const [TypeOption, setTypeOption] = useState<SelectProps["options"]>([]);
  const [PageSize] = useState(30);
  const [PageNum, setPageNum] = useState(1);
  const [SelectName, setSelectName] = useState("");
  const onFinish = (values: any) => {
    console.log("Received values of form: ", values);
  };

  const selectList = [
    "后端",
    "前端",
    "Android",
    "iOS",
    "人工智能",
    "开发工具",
    "代码人生",
    "阅读",
  ];
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  const GetLabelList = async (type: number) => {
    const params = {
      PageSize: PageSize,
      PageNum: PageNum,
    };
    const res: any = await GetLabelListApi(params);
    console.log("获取到标签", res);
    if (res.status === 0) {
      if (type) {
        let NewList = TypeOption?.concat(res.LabelList);
        setTypeOption(NewList);
      } else {
        setTypeOption(res.LabelList);
      }
    }
  };

  const handlePreview = async (file: any) => {
    const form = new FormData();
    form.append("file", file.file);
    const res: any = await UploadApi(form);
    console.log("上传结果", res);
    if (res.status === 0) {
      const FileList = [
        {
          uid: "1",
          name: res.name,
          url: res.url,
        },
      ];
      setFileList(FileList);
    }
    return false;
  };

  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };
  const onPackagePopupScroll = async (e: any) => {
    const { target } = e;
    // 判断是否滑动到底部 滚动条顶部距离 + 下拉栏展示高度 = 滚动总高度
    if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
      // 滑动到底部实现分页加载逻辑
      console.log("到底部了");
      setPageNum((PageNum) => PageNum + 1);
      GetLabelList(1);
    }
  };

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as FileType);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const SendArticle = async () => {
    const FormData = form.getFieldsValue();
    if (SelectName === "") {
      message.error("请选择文章分类");
    } else if (!FormData.ArticleTabs) {
      message.error("请添加文章标签");
    } else if (fileList.length === 0) {
      message.error("请上传文章封面");
    } else if (!FormData.intro) {
      message.error("请编辑文章摘要");
    } else if (props.Title === "") {
      message.error("标题不能为空");
    } else if (props.Content === "") {
      message.error("正文内容不能为空");
    } else {
      const params = {
        ArticleTitle: props.Title,
        Abstract: FormData.intro || "",
        ArticleContent: props.Content,
        ArticleImgUrl: fileList ? fileList[0].url : "",
        ArticleTabs: FormData.ArticleTabs || [],
        ArticleType: SelectName,
      };
      const res: any = await CreateArticleApi(params);
      console.log("创建文章结果", res);
      if (res.status === 0) {
        message.success("文章提交成功!");
        navigate("/published", { state: { articleName: props.Title } });
        dispatch(setOpen(false));
      }
    }
  };

  const selectItem = (item: string) => {
    console.log(item, "333");
    setSelectName(item);
  };

  const Footer = (
    <div className={publishDrawerLess.publishDrawer_bottom_btn}>
      <div className="send_btn">
        <Button
          style={{ marginRight: "20px" }}
          onClick={() => dispatch(setOpen(false))}
        >
          取消
        </Button>
        <Button type="primary" onClick={SendArticle}>
          确认并发布
        </Button>
      </div>
    </div>
  );
  const onClose = () => {
    dispatch(setOpen(false));
  };

  useEffect(() => {
    GetLabelList(0);
  }, []);
  return (
    <>
      <Drawer
        title="发布文章"
        onClose={onClose}
        placement="right"
        open={openFlag}
        footer={Footer}
        width="590"
      >
        <Form
          {...formItemLayout}
          form={form}
          name="register"
          onFinish={onFinish}
          initialValues={{}}
          scrollToFirstError
          labelAlign="right"
          labelCol={{ span: 4, offset: 1 }}
        >
          <Form.Item
            name="ArticleType"
            label="分类"
            rules={[
              {
                required: true,
                message: "请选择文章分类",
              },
            ]}
          >
            <div
              className={publishDrawerLess.richTextEditor_form_select_content}
            >
              {selectList.map((item: string, index: number) => {
                return (
                  <div
                    className={[
                      SelectName == item ? "active_select_items" : "",
                      "select_items",
                    ].join(" ")}
                    key={index}
                    onClick={() => selectItem(item)}
                  >
                    {item}
                  </div>
                );
              })}
            </div>
          </Form.Item>
          <Form.Item
            name="ArticleTabs"
            label="添加标签"
            rules={[{ required: true, message: "请搜索添加标签" }]}
          >
            <Select
              mode="tags"
              style={{ width: "100%" }}
              placeholder="请搜索添加标签"
              onChange={handleChange}
              options={TypeOption}
              showSearch // 支持搜索
              allowClear // 支持清除所选项
              onPopupScroll={onPackagePopupScroll}
              listHeight={300} // select下拉栏展示高度
              fieldNames={{ label: "LavbelName", value: "LavbelName" }}
            />
          </Form.Item>
          <Form.Item
            name="ArticleImgUrl"
            label="文章封面"
            rules={[{ required: true, message: "请上传文章封面" }]}
          >
            <ImgCrop rotationSlider aspect={200 / 100}>
              <Upload
                accept="image/*"
                listType="picture-card"
                fileList={fileList}
                onChange={onChange}
                onPreview={onPreview}
                customRequest={handlePreview}
              >
                {fileList.length < 1 && "+ 上传封面"}
              </Upload>
            </ImgCrop>
          </Form.Item>

          <Form.Item
            name="intro"
            label="编辑摘要"
            rules={[{ required: true, message: "请编辑您的文章摘要" }]}
          >
            <Input.TextArea
              rows={4}
              variant="filled"
              showCount
              maxLength={100}
            />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
}

export default PublishDrawer;
